#!/usr/bin/env python3

# Angry Words, the word replacement game

import sys

def usage():
    print("Wrong usage")
    exit(0)

def run_game(s):
    # This regex may be useful, not sure '\[[^>]*\]'
    blank_list = []
    for i in s.split('\n'):
        # This loop searches for each blank tag
        in_tag = False
        for n in range(len(i)):
            if in_tag:
                if i[n] == ']':
                    # Join the list of characters in the tag
                    blank_list[-1] = ''.join(blank_list[-1])
                    in_tag = False
                else:
                    # Keep reading a tag until a ] is reached
                    blank_list[-1].append(i[n])
            elif i[n] == '[':
                # [ indicates beginning of a tag
                blank_list.append([])
                in_tag = True
    filled_in = fill_in(blank_list)
    filled_in.reverse() # This is to make popping easier
    print('\n\n')
    for i in s.split('\n'):
        in_tag = False
        for n in range(len(i)):
            if in_tag:
                if i[n] == ']':
                    # At the end of the tag, pop the last word
                    print(filled_in.pop(), end='')
                    in_tag = False
            elif i[n] == '[':
                in_tag = True
            else:
                print(i[n], end='')
        print()

def fill_in(bl):
    # This function gets the user's input for each blank
    result = []
    for i in range(len(bl)):
        result.append(input('{0:2}. {1:21}: '.format(i+1,bl[i])))
    return result

def play_file(filepath):
    f = open(filepath, 'r')
    s = f.read()
    f.close()
    try:
        run_game(s)
    except (KeyboardInterrupt, EOFError) as e:
        print("\n\nInterrupt")
        exit(0)

def parse_tsv(s):
    result = [i.split('\t') for i in s.split('\n')]
    return list(filter(lambda x: x != [''], result))

def play_loop():
    games_table = []
    try:
        f = open("templates/files.tsv")
        s = f.read()
        f.close()
        games_table = parse_tsv(s)[1:]
    except FileNotFoundError as e:
        print("templates/files.tsv not found")
    table_size = len(games_table)
    prompt = '\nEnter the number of the template you wish to play: '
    while True:
        print('\n  0. Exit the program')
        for i in range(table_size):
            print('{0:3}. {1}'.format(i+1,games_table[i][1]))
        try:
            user_result = int(input(prompt))
            if user_result == 0:
                exit(0)
            if user_result < 0:
                raise ValueError
            play_file('templates/' + games_table[user_result-1][0])
        except (KeyboardInterrupt, EOFError) as e:
            print("\n\nInterrupt")
            exit(0)
        except (IndexError, ValueError) as e:
            print("\nPlease enter an integer between 0 and {0}.".format(table_size))

def main():
    if len(sys.argv) < 2:
        play_loop()
    elif len(sys.argv) == 2:
        play_file(sys.argv[1])
    else:
        usage()

if __name__ == '__main__':
    main()
